//
//  MyApplyViewController.m
//  ZhouProject
//
//  Created by Dlrj on 14-12-15.
//  Copyright (c) 2014年 admin. All rights reserved.
//

#import "MyApplyViewController.h"
#import "LoadingHelper.h"
#import "NetWorkingHelper.h"
#import "MyApply.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "Reachability.h"
#import "GeRenGuanZhuTableViewCell.h"
#import "UIScrollView+MJRefresh.h"
#import "XiuGaiXinXi.h"

#define rowNum 3

static NSString *cellReuseIdentifier = @"cellReuseIdentifier";

@implementation MyApplyViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeValue:) name:@"UpdateInfoSuccess" object:nil];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"我的应用";
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kH(0), kScreenWidth ,kH(520))];;
    tableView.delegate = self;
    tableView.dataSource = self;
    _scrView = tableView;
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    tableView.separatorColor = [UIColor clearColor];
    
    UINib *myNib = [UINib nibWithNibName:@"GeRenGuanZhuTableViewCell" bundle:nil];
    
    [tableView registerNib:myNib forCellReuseIdentifier:cellReuseIdentifier];
    [self.view addSubview:tableView];
    
    [LoadingHelper showLoadingWithView:self.view];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        _arr = [NetWorkingHelper MyApplyWithcategoryId:self.strcategoryId];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //刷新列表
            [_scrView reloadData];
            
            [LoadingHelper hiddonLoadingWithView:self.view];
            
            [_scrView addHeaderWithTarget:self action:@selector(headerRereshing)];
            
        });
    });    
}

- (void)changeValue:(NSNotification *)notificaion{
    NSDictionary * userInfo = notificaion.userInfo;
    XiuGaiXinXi * model = [userInfo objectForKey:@"return"];
    self.strcategoryId = model.strTypeid;
}


-(void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        _arr = [NetWorkingHelper MyApplyWithcategoryId:self.strcategoryId];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //刷新列表
            [_scrView reloadData];
            
            [_scrView headerEndRefreshing];
            
        });
    });
}

-(void)click:(UIButton*)sender
{
    NSLog(@"%d",sender.tag);
    MyApply * model = [_arr objectAtIndex:sender.tag-100];
    
    //获取app本地打开的url
    NSURL *url1 = [NSURL URLWithString:model.strappPackage];
  
    //app已安装
    if([[UIApplication sharedApplication] canOpenURL:url1]) {
        //打开app
        [[UIApplication sharedApplication] openURL:url1];
    }
    //app未安装
    else {
        //在wifi环境下
        if ([self isConnectionAvailable]) {
            //下载app
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:model.strappPath]];
        }
        else {
            //提示是否下载app
            _str = model.strappPath;
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您现在不在wifi环境下是否下载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"下载", nil];
            alert.tag = 100;
            [alert show];
        }
    }
}

//提示框的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //不在wifi环境下是否下载app
    if (alertView.tag == 100) {
        //下载
        if (buttonIndex == 1) {
            //下载app
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_str]];
        }
    }
}

//判断是否在wifi环境下
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = NO;
            NSLog(@"3G");
            break;
    }
    
    return isExistenceNetwork;
}

#pragma mark - tableView数据源方法

#pragma UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //存在数据
    if (_arr) {
        return (_arr.count%rowNum>0?(_arr.count/rowNum+1):_arr.count/rowNum)+1;
    }else{
        return 1;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GeRenGuanZhuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier];
    if (cell == nil) {
        cell = [[GeRenGuanZhuTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseIdentifier];
        //                    lab.layer.borderWidth = 1.0f;//边框宽度
        //                    lab.layer.borderColor = [UIColor colorWithRed:212.0 / 255 green:212.0 / 255 blue:212.0 / 255 alpha:1].CGColor;//边框颜色
        //                    lab.layer.cornerRadius = 5.0;//设置圆角
        //内容不超出边框
        cell.nameLabel1.clipsToBounds = YES;
        cell.nameLabel2.clipsToBounds = YES;
        cell.nameLabel3.clipsToBounds = YES;
    }
    //默认第一行不显示
    if (indexPath.row==0) {
        cell.nameLabel1.hidden = YES;
        cell.nameLabel2.hidden = YES;
        [cell.nameLabel3 setHidden:YES];
        cell.headImage1.hidden = YES;
        cell.headImage2.hidden = YES;
        [cell.headImage3 setHidden:YES];
        return cell;
    }
    
    int i = indexPath.row-1;
    
    //控制第2列的显示与隐藏
    if (_arr.count > (i*rowNum+1)) {
        [cell.headImage2 setHidden:NO];
        [cell.nameLabel2 setHidden:NO];
        MyApply * model2 = [_arr objectAtIndex:i*rowNum+1];
        NSString * str  = [NSString stringWithFormat:@"%@%@",basePath,model2.strappIcon];
        UIImage *image2 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
        if (image2) {
            [cell.headImage2 setImage:image2];
        }
//        [cell.headImage2 sd_setImageWithURL:[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]  placeholderImage:[UIImage imageNamed:@"morentu.png"]];
        cell.nameLabel2.text = model2.strappName;
        [cell.headerButton2 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        cell.headerButton2.tag = 100+i*rowNum+1;

    }
    else {
        [cell.headImage2 setHidden:YES];
        [cell.nameLabel2 setHidden:YES];
        [cell.headerButton2 removeTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    //控制第3列的显示与隐藏
    if (_arr.count > (i*rowNum+2)) {
        [cell.headImage3 setHidden:NO];
        [cell.nameLabel3 setHidden:NO];
        MyApply * model3 = [_arr objectAtIndex:i*rowNum+2];
        NSString * str  = [NSString stringWithFormat:@"%@%@",basePath,model3.strappIcon];
        UIImage *image3 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
        if (image3) {
            [cell.headImage3 setImage:image3];
        }
//        [cell.headImage3 sd_setImageWithURL:[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]  placeholderImage:[UIImage imageNamed:@"morentu.png"]];
        cell.nameLabel3.text = model3.strappName;
        [cell.headerButton3 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        cell.headerButton3.tag = 100+i*rowNum+2;
        
    }
    else {
        [cell.headImage3 setHidden:YES];
        [cell.nameLabel3 setHidden:YES];
        [cell.headerButton3 removeTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    MyApply * model1 = [_arr objectAtIndex:i*rowNum];
    NSString * str  = [NSString stringWithFormat:@"%@%@",basePath,model1.strappIcon];
    UIImage *image1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
    if (image1) {
        [cell.headImage1 setImage:image1];
    }
//    [cell.headImage1 sd_setImageWithURL:[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]  placeholderImage:[UIImage imageNamed:@"morentu.png"]];
    cell.nameLabel1.text = model1.strappName;
    [cell.headerButton1 addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    cell.headerButton1.tag = 100+i*rowNum;
    
//    UIButton * btn = [UIButton  buttonWithType:UIButtonTypeCustom];
//    btn.backgroundColor = [UIColor clearColor];
//    btn.frame = CGRectMake(kW(40+145*j), kH(84+140*i), kW(95), kH(120));
//    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
//    btn.tag = 100+a;
//    a++;
//    [_scrView addSubview:btn];
//    if (a == _arr.count) {
//        NSLog(@"%d",i);
//        if (i > 2) {
//            [_scrView setContentSize:CGSizeMake(kScreenWidth, kH(520 + 140 * (i-2)))];
//        }
//        return;
//    }

//    [cell.guanZhuButton addTarget:self action:@selector(click1:) forControlEvents:UIControlEventTouchUpInside];
//    cell.guanZhuButton.tag = indexPath.row;
    
    return cell;
}

//TableViewCell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //默认第一行不显示
    if (indexPath.row==0) {
        return 40;
    }
    return 90;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

//禁止点击变暗
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
